import os

def extract_kdoc_comments(content: str):
    """从 Kotlin 源文件中提取 KDoc 注释内容，保留 ``` 代码块缩进"""
    comments = []
    i = 0
    n = len(content)
    while i < n:
        if content.startswith("/**", i):
            i += 3
            buf = []
            in_codeblock = False
            while i < n:
                if content.startswith("```", i):
                    in_codeblock = not in_codeblock
                    buf.append("```")
                    i += 3
                    continue
                if not in_codeblock and content.startswith("*/", i):
                    i += 2
                    break
                buf.append(content[i])
                i += 1
            raw_comment = "".join(buf)

            lines = []
            for line in raw_comment.splitlines():
                stripped = line.lstrip()
                if not in_codeblock:
                    if stripped.startswith("*"):
                        stripped = stripped[1:].lstrip()
                else:
                    if stripped.startswith("*"):
                        idx = line.index("*")
                        stripped = line[idx+1:]  # 保留缩进

                # 确保 ``` 行没有多余空格
                if stripped.strip().startswith("```"):
                    stripped = stripped.strip()
                    in_codeblock = not in_codeblock

                lines.append(stripped)

            cleaned = "\n".join(lines).strip()
            if cleaned:
                comments.append(cleaned)
        else:
            i += 1
    return comments



def process_file(src_path: str, dst_root: str):
    with open(src_path, "r", encoding="utf-8") as f:
        content = f.read()

    comments = extract_kdoc_comments(content)
    if not comments:
        return

    rel_path = os.path.relpath(src_path)
    dst_path = os.path.join(dst_root, os.path.splitext(rel_path)[0] + ".md")
    os.makedirs(os.path.dirname(dst_path), exist_ok=True)

    with open(dst_path, "w", encoding="utf-8") as f:
        f.write("\n\n".join(comments))


def process_dir(src_root: str, dst_root: str):
    for root, _, files in os.walk(src_root):
        for file in files:
            if file.endswith(".kt"):
                process_file(os.path.join(root, file), dst_root)


if __name__ == "__main__":
    src_root = "./"      # 源码目录
    dst_root = "./docs"  # 输出目录
    process_dir(src_root, dst_root)
